import json

from flask import Blueprint, render_template, request, session, redirect, url_for, jsonify
from .db import get_db
from .decorator import login_required
from .model import CourseModel

course_bp = Blueprint('course', __name__)

@course_bp.route('/course', methods=['GET'])
@login_required
def index():
    return render_template('course/index.html')

@course_bp.route('/course/add', methods=['GET'])
def add():
    return render_template('course/add.html')

@course_bp.route('/course/delete/<int:id>', methods=['DELETE'])
def delete(id):
    get_db().execute("delete from course where id=?", (id,))
    get_db().commit()
    return jsonify({})

@course_bp.route('/course/save', methods=['POST'])
def save():
    course = request.json
    get_db().execute('insert into course (name, hours) values (?, ?)', (course['name'], course['hours']))
    get_db().commit()
    return json.dumps({})

@course_bp.route('/course/all', methods=['GET'])
@login_required
def all_courses():
    courses = CourseModel().query.all()
    # 模型转成字典后返回json数据
    courses_list = [course.to_dict() for course in courses]
    return json.dumps(courses_list)


